package org.momonga1banchi.reminder.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;

public class MailUtil {

    public static String getMailBodyMessage(Part part) throws MessagingException, IOException {
        // マルチパートの場合
        if (part.isMimeType("multipart/*")) {
            Multipart content = (Multipart) part.getContent();

            StringBuilder sb = new StringBuilder();
            // 含まれるパートを再帰的に処理
            int count = content.getCount();
            for (int i = 0; i < count; i++) {
                sb.append(getMailBodyMessage(content.getBodyPart(i)));
            }
            return sb.toString();
        }
        // テキストの場合
        else if (part.isMimeType("text/plain")) {
            InputStream is = (InputStream) part.getInputStream();
            Reader r = null;
            String contentType = part.getContentType();
            if (contentType.contains("UTF-8") || contentType.contains("utf-8")) {
//                MyLog.log.info("content type is utf-8 [" + contentType + "]");
                r = new InputStreamReader(is, "utf-8");
            } else if (contentType.contains("ISO-2022-JP") || contentType.contains("iso-2022-jp")) {
//                MyLog.log.info("content type is iso-2022-jp [" + contentType + "]");
                r = new InputStreamReader(is, "iso-2022-jp");
            } else if (contentType.contains("ISO-8859-1") || contentType.contains("iso-8859-1")) {
//                MyLog.log.info("content type is iso-8859-1 [" + contentType + "]");
                r = new InputStreamReader(is, "iso-8859-1");
            } else {
//                MyLog.log.warn("content type is unknown [" + contentType + "]");
                r = new InputStreamReader(is, "iso-2022-jp");
            }

            BufferedReader buf = new BufferedReader(r);

            // テキスト内容を取得
            StringBuilder sb = new StringBuilder();
            for (String line; (line = buf.readLine()) != null;) {
                sb.append(line + "\n");
            }

            String msgBody = sb.length() > 0 ? sb.substring(0, sb.length() - 1) : sb.toString();
//            MyLog.log.info("include msgs=\n" + msgBody);
            return msgBody;
        } else {
            // 添付ファイルは読み飛ばす
            return "";
        }
    }
}
